﻿using Core.Identity.Organizations.Features.Commands.BatchDelete;
using Core.Identity.Organizations.Features.Commands.Create;
using Core.Identity.Organizations.Features.Commands.Update;
using Core.Identity.Organizations.Features.Queries.GetAll;
using Infrastructure.Auth.Policy;
using MediatR;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;

namespace Infrastructure.Identity.Organizations.Endpoints;

/// <summary>
/// 组织机构管理端点
/// </summary>
public static class OrganizationEndpoints
{
    /// <summary>
    /// 映射组织机构相关API端点
    /// </summary>
    public static IEndpointRouteBuilder MapOrganizationEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/api/organization")
            .WithTags("Organization")
            .WithDescription("组织机构管理相关接口");

        // -----------------------
        // 获取全部组织机构
        // GET /api/organization
        // -----------------------
        group.MapGet("/", async ([FromServices] IMediator mediator) =>
            await mediator.Send(new GetAllOrganizationsQuery()))
            .RequirePermission("Organization:View:All")
            .WithDescription("查询全部组织机构")
            .WithMetadata(new EndpointNameMetadata("GetAllOrganizations"));

        // -----------------------
        // 创建组织机构
        // POST /api/organization
        // -----------------------
        group.MapPost("/", async (
            [FromBody] CreateOrganizationCommand request,
            [FromServices] IMediator mediator) =>
            await mediator.Send(request))
            .RequirePermission("Organization:Create")
            .WithDescription("创建组织机构")
            .WithMetadata(new EndpointNameMetadata(nameof(CreateOrganizationCommand)));

        // -----------------------
        // 修改组织机构
        // PUT /api/organization/{id}
        // -----------------------
        group.MapPut("/{id:guid}", async (
            Guid id,
            [FromBody] UpdateOrganizationCommand request,
            [FromServices] IMediator mediator) =>
            await mediator.Send(request))
            .RequirePermission("Organization:Update")
            .WithDescription("修改组织机构")
            .WithMetadata(new EndpointNameMetadata(nameof(UpdateOrganizationCommand)));

        // -----------------------
        // 批量删除组织机构
        // DELETE /api/organization
        // -----------------------
        group.MapDelete("/", async (
            [FromBody] BatchDeleteOrganizationCommand request,
            [FromServices] IMediator mediator) =>
            await mediator.Send(request))
            .RequirePermission("Organization:Delete")
            .WithDescription("批量删除组织机构")
            .WithMetadata(new EndpointNameMetadata(nameof(BatchDeleteOrganizationCommand)));

        return app;
    }
}
